package com.sy.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sy.EmployeeService;
import com.sy.constant.JwtClaimsConstant;
import com.sy.context.BaseContext;
import com.sy.dto.EmployeeDTO;
import com.sy.dto.EmployeeLoginDTO;
import com.sy.dto.EmployeePageQueryDTO;
import com.sy.pojo.Employee;
import com.sy.properties.JwtProperties;
import com.sy.result.PageResult;
import com.sy.result.Result;
import com.sy.utils.JwtUtil;
import com.sy.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工管理
 */
@Api(tags = "员工相关接口")
@RestController
@RequestMapping("/admin/employee")
@Slf4j
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;



    /**
     * 登录
     * @param employeeLoginDTO
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO, HttpSession session) {
        log.info("员工登录：{}", employeeLoginDTO);
        Employee employee = employeeService.login(employeeLoginDTO);
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 退出
     * @return
     */
    @ApiOperation("登出")
    @PostMapping("/logout")
    public Result<String> logout() {
        //打印请求数据日志
        log.info("员工退出系统成功...");
        return Result.success();
    }

    /**
     * 员工分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @ApiOperation("员工分页查询")
    @GetMapping("/findAll")
    public Result<PageResult> findAll(EmployeePageQueryDTO employeePageQueryDTO){
        log.info("员工分页查询：{}", employeePageQueryDTO);
        PageResult pageResult = employeeService.findAll(employeePageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 判断手机号是否存在的方法
     * @param phone
     * @return
     */
    @ApiOperation("判断手机号是否存在的方法")
    @GetMapping("/doExistPhone")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "要验证的手机号",name = "phone",
                    required = true,
                    dataTypeClass =String.class)
    })
    public Result<String> doExistPhone(String phone){
        log.info("判断手机号是否存在的方法：{}", phone);
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getPhone, phone);
        Employee employee = employeeService.getOne(queryWrapper);
        if (employee == null){
            return Result.success();
        }else {
            return Result.error("手机号已存在");
        }
    }

    /**
     * 判断用户名是否存在的方法
     * @param username
     * @return
     */
    @ApiOperation("判断用户名是否存在的方法")
    @GetMapping("/doExistUsername")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "要验证的用户名",name = "username",
                    required = true,
                    dataTypeClass =String.class)
    })
    public Result<String> doExistUsername(String username){
        log.info("判断用户名是否存在的方法：{}", username);
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, username);
        Employee employee = employeeService.getOne(queryWrapper);
        if (employee == null){
            return Result.success();
        }else {
            return Result.error("用户名已存在");
        }
    }

    /**
     * 新增员工
     * @param employeeDTO
     * @return
     */
    @ApiOperation("新增员工")
    @PostMapping("save")
    public Result save(@RequestBody EmployeeDTO employeeDTO){
        try {
            log.info("新增员工：{}", employeeDTO);
            employeeService.saveEmp(employeeDTO);
        } catch (Exception e) {
            throw new RuntimeException("新增员工失败");
        }
        return Result.success("新增员工成功");
    }

    /**
     * 修改员工
     * @param employeeDTO
     * @return
     */
    @ApiOperation("修改员工")
    @PostMapping("update")
    public Result update(@RequestBody EmployeeDTO employeeDTO){
        try {
            log.info("修改员工：{}", employeeDTO);
            Employee employee = new Employee();
            BeanUtils.copyProperties(employeeDTO,employee);
            employee.setUpdateTime(LocalDateTime.now());
            employee.setUpdateUser(BaseContext.getCurrentId());
            employeeService.updateById(employee);
        } catch (BeansException e) {
            throw new RuntimeException("员工修改失败");
        }
        return Result.success("修改员工成功");
    }

    /**
     * 删除员工
     * @param ids
     * @return
     */
    @ApiOperation("删除员工")
    @PostMapping("delete")
    @ApiImplicitParam(value = "是一个list集合，存储要删除的数据",name = "ids",
            required = true,dataTypeClass = List.class)
    public Result delete(@RequestBody List<Long> ids){
        log.info("删除员工：{}" + ids);
        try {
            Long empId = BaseContext.getCurrentId();
            if (ids.contains(empId)){
                return Result.error("删除自己不能删除");
            }else {
                QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("id",ids);
                Employee employee = new Employee();
                employee.setIsDelete(0);
                employee.setUpdateTime(LocalDateTime.now());
                employee.setUpdateUser(empId);
                employeeService.update(employee,queryWrapper);
                return Result.success();
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException("删除异常");
        }
    }
}
